//插件文档: https://ext.dcloud.net.cn/plugin?id=392
import Request from '@/common/luch-request/request.js'
import CONSTS from '@/common/consts.js'
const instance = new Request();

let requestUrlWithoutToken = [
	// "/login/msg",
	// "/login/pwd",
];

let globalConfig = {
	// #ifdef H5
	baseUrl: CONSTS.STATICHOST,
	// #endif
	// #ifdef APP-PLUS || MP-WEIXIN
	baseUrl: CONSTS.STATICHOST,
	// #endif
	header: {
		// 'content-type': 'application/x-www-form-urlencoded',
		'Content-Type': 'application/json; charset=utf-8',
		// 'content-type': 'application/json; charset=utf-8',
		
		
	},
};

function setToken(e) {
	//test12432
	uni.setStorageSync('token', e);
}

function getToken() {
	return uni.getStorageSync('token');
}

instance.setConfig((config) => { /* 设置全局配置 */
	config.baseUrl = globalConfig.baseUrl
	config.header = {
		...config.header,
		...globalConfig.header
	}
	return config
})

/**
 * 自定义验证器，如果返回true 则进入响应拦截器的响应成功函数(resolve)，否则进入响应拦截器的响应错误函数(reject)
 * @param { Number } statusCode - 请求响应体statusCode（只读）
 * @return { Boolean } 如果为true,则 resolve, 否则 reject
 */
instance.validateStatus = (statusCode) => {
	return statusCode === 200
}

instance.interceptor.request((config, cancel) => { /* 请求之前拦截器 */
	let header = config.custom.header || {};
	let token = getToken();
	// console.log("request")
	// console.log(config)
		
	if (!token && !requestUrlWithoutToken.indexOf(config.url)) {
		uni.navigateTo({
			url: '/pages/login/login'
		});
	}
	config.header = {
		...config.header,
		...header,
		// Authorization: token,
		Authorization:'Bearer'+' '+token,
	}

	return config
})

instance.interceptor.response((response) => { /* 请求之后拦截器 */
	if (response.data.code === '000015') {
		uni.navigateTo({
			url: '/pages/login/index'
		});
		return Promise.reject(response);
	}
	if (response.data.code != '000000') {
		// return Promise.reject(response)
		let result = {
			code: response.data.code,
			message: response.data.msg,
			data:response.data.data,
		};
		uni.hideToast();
		uni.showToast({
			title: result.message,
			icon: 'none'
		});

		return result;
	}
	return response.data
}, (response) => { // 请求错误做点什么

	switch (response.statusCode) {
		case 401:
			uni.navigateTo({
				url: '/pages/login/index'
			});
			break;
		default:
			break;
	}
	let result = new Object()
	result.code = '999999';
	result.msg = "请检查网络"
	return result;

	// return response
})


function send(method, url, data = {}, params = {}, custom = {}) {
	let prom = instance.request({
		method: method.toUpperCase(), // 请求方法必须大写
		url,
		data,
		// params会拼接到url上
		params,
		// 可以加一些自定义参数，在拦截器等地方使用
		custom,
	})

	return prom;

}

// 具体文档参照uni的上传下载 https://uniapp.dcloud.io/api/request/network-file
// 直接发起一个 multipart/form-data 的 post请求
function upload(url, filePath, otherFormData = {}, complete = (res) => {}) {
	//在这里可以获取token塞进header
	let header = {
		Authorization: getToken()
	};

	let uploadTask = uni.uploadFile({
		url: `${globalConfig.baseUrl}${url}`,
		filePath,
		name: 'file',
		header: {
			...globalConfig.header,
			...header
		},
		formData: otherFormData,
		complete,
	});
	// uploadTask.abort(); 中断上传
	// uploadTask.onProgressUpdate(callback); 监听进度

	return uploadTask;
}

// 具体文档参照uni的上传下载 https://uniapp.dcloud.io/api/request/network-file
// 直接发起一个get请求
function download(url, complete = (res) => {}) {
	//在这里可以获取token塞进header
	let header = {
		Authorization: getToken()
	};

	let downloadTask = uni.downloadFile({
		url: `${globalConfig.baseUrl}${url}`,
		header: {
			...globalConfig.header,
			...header
		},
		complete,
	});

	// downloadTask.abort(); 中断下载
	// downloadTask.onProgressUpdate(callback); 监听进度

	return downloadTask;
}

export default {
	send,
	upload,
	download,
	setToken,
	getToken
}
